package cn.zzf.core;

import cn.zzf.mapper.*;
import cn.zzf.po.*;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.util.*;

/**
 * @description: 将爬取的数据写入导数据库,待重构
 * @author GaoFeng2017
 * @date 2018-02-14 21:37:50
 **/

public class LessonWriteToDb {
    private List<List<LessonItem>> lessonItems;
    private List<TeacherInfo> teacherInfos;

    public LessonWriteToDb(List<List<LessonItem>> lessonItems, List<TeacherInfo> teacherInfos) {
        this.lessonItems = lessonItems;
        this.teacherInfos = teacherInfos;
    }

    public void writeAll() throws IOException {

        //插入教师信息
        if (teacherInfos != null) {
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
                    .build(Resources.getResourceAsStream("mybatis.xml"));

            /*dao类*/
            SqlSession sqlSession = sessionFactory.openSession();
            TeacherInfoMapper mapper = sqlSession.getMapper(TeacherInfoMapper.class);
            TeacherLessonMapper teacherLessonMapper = sqlSession.getMapper(TeacherLessonMapper.class);
            ClassroomInfoMapper classroomInfoMapper = sqlSession.getMapper(ClassroomInfoMapper.class);
            ClassInfoMapper classInfoMapper = sqlSession.getMapper(ClassInfoMapper.class);
            TeacherLessonClassNexusMapper teacherLessonClassNexusMapper = sqlSession.getMapper(TeacherLessonClassNexusMapper.class);
            TeacherClassNexusMapper teacherClassNexusMapper = sqlSession.getMapper(TeacherClassNexusMapper.class);

            int index = 0;
            if (lessonItems != null) {
                for (List<LessonItem> itemList : lessonItems) {
                    TeacherInfo ti = teacherInfos.get(index);
                    mapper.insertSelective(ti);
                    System.out.println(index);
                    for (LessonItem item : itemList) {
                        TeacherLesson teacherLesson = new TeacherLesson();
                        teacherLesson.setGmtCreate(new Date());
                        teacherLesson.setName(item.getLessonName());
                        teacherLesson.setTeacherId(ti.getId());
                        teacherLesson.setYearTermId((long) 1);

                        int weekday = 0;

                        switch (item.getWeekday()) {
                            case "星期一":
                                weekday = 1;
                                break;
                            case "星期二":
                                weekday = 2;
                                break;
                            case "星期三":
                                weekday = 3;
                                break;
                            case "星期四":
                                weekday = 4;
                                break;
                            case "星期五":
                                weekday = 5;
                                break;
                            case "星期六":
                                weekday = 6;
                                break;
                            case "星期日":
                                weekday = 7;
                                break;
                        }

                        teacherLesson.setWeekday((byte) weekday);

                        /*周次类型*/
                        String week = item.getWeekInfo();
                        if (week.contains("单周")) {
                            teacherLesson.setWeekType((byte) 1);
                        } else if (week.contains("双周")) {
                            teacherLesson.setWeekType((byte) 2);
                        } else if (week.contains("周")) {
                            teacherLesson.setWeekType((byte) 0);
                        } else {
                            throw new RuntimeException("周次错误");
                        }

                        /*校区*/
                        if (item.getCampus().contains("十里")) {
                            teacherLesson.setCampus((byte) 0);
                        } else if (item.getCampus().contains("濂溪")) {
                            teacherLesson.setCampus((byte) 1);
                        } else if (item.getCampus().contains("混合")) {
                            teacherLesson.setCampus((byte) 2);
                        } else {
                            throw new RuntimeException(ti.getName() + item.getCampus() + "校区错误");
                        }

                        teacherLesson.setPeriod(formatPeriod(item.getPeriod()));

                        /*教室*/
                        String[] classroomAndClass = formatClassroomAndClass(item.getClassroomAndClass());


                        if (!Objects.equals(classroomAndClass[0],"")) {
                            ClassroomInfoExample classroomInfoExample = new ClassroomInfoExample();
                            ClassroomInfoExample.Criteria criteria1 = classroomInfoExample.createCriteria();
                            criteria1.andNameEqualTo(classroomAndClass[0]);
                            List<ClassroomInfo> classroomInfos = classroomInfoMapper.selectByExample(classroomInfoExample);

                            if (classroomInfos.isEmpty()) {
                                ClassroomInfo classroomInfo = new ClassroomInfo();
                                classroomInfo.setGmtCreate(new Date());
                                classroomInfo.setName(classroomAndClass[0]);
                                classroomInfo.setDescription("投影课教室");
                                classroomInfoMapper.insertSelective(classroomInfo);
                                teacherLesson.setClassroomId(classroomInfo.getId());
                            } else {
                                teacherLesson.setClassroomId(classroomInfos.get(0).getId());
                            }
                        }

                        week = week.replaceAll("(单周)|(双周)|(周)", "")
                                .replaceAll("\\s{1}", "");


                        /*周次*/
                        List<Byte[]> weekItems = formatWeek(week);
                        /*if (ti.getName().equals("吴政") && teacherLesson.getPeriod().equals("7-8")) {
                            System.out.println(weekItems);
                            System.out.println(weekItems.size());
                            System.out.println(week);
                            System.exit(0);
                        }*/

                        /*TeacherLessonWeek lessonWeek = new TeacherLessonWeek();
                        lessonWeek.setBeginWeek(is[0]);
                        lessonWeek.setEndWeek(is[1]);
                        lessonWeek.setGmtCreate(new Date());
                        lessonWeek.setTeacherLessonId(teacherLesson.getId());
                        lessonWeekMapper.insertSelective(lessonWeek);*/


                        /*班级*/
                        for (Byte[] is : weekItems) {
                            for (Byte ii = is[0]; ii <= is[1]; ii++) {
                                if (teacherLesson.getWeekType() == 1 && ii % 2 == 0) {
                                    continue;
                                } else if (teacherLesson.getWeekType() == 2 && ii % 2 == 1) {
                                    continue;
                                }
                                teacherLesson.setWeek(ii);
                                teacherLessonMapper.insertSelective(teacherLesson);
                                for (int i = 1; classroomAndClass != null && i < classroomAndClass.length; i++) {
                                    String classItem = classroomAndClass[i].trim();

                                    ClassInfoExample classInfoExample = new ClassInfoExample();
                                    ClassInfoExample.Criteria classInfoExampleCriteria = classInfoExample.createCriteria();
                                    classInfoExampleCriteria.andNameEqualTo(classItem);
                                    List<ClassInfo> classInfo1 = classInfoMapper.selectByExample(classInfoExample);

                                    if (!classInfo1.isEmpty()) {

                                        System.out.println("classInfo1::" + classInfo1.get(0).getId() + " :: size" + classInfo1.size());
                                        TeacherClassNexusExample teacherClassNexusExample = new TeacherClassNexusExample();
                                        TeacherClassNexusExample.Criteria criteria = teacherClassNexusExample.createCriteria();
                                        criteria.andClassIdEqualTo(classInfo1.get(0).getId()).andTeacherIdEqualTo(ti.getId());
                                        List<TeacherClassNexus> teacherClassNexuses = teacherClassNexusMapper.selectByExample(teacherClassNexusExample);

                                        TeacherClassNexus teacherClassNexus = new TeacherClassNexus();
                                        teacherClassNexus.setGmtCreate(new Date());
                                        teacherClassNexus.setTeacherId(ti.getId());

                                        if (teacherClassNexuses.isEmpty()) {
                                            System.out.println("teacherClassNexuses.isEmpty()" + classInfo1.get(0).getId());
                                            teacherClassNexus.setClassId(classInfo1.get(0).getId());
                                            teacherClassNexusMapper.insertSelective(teacherClassNexus);
                                        }

                                        TeacherLessonClassNexus teacherLessonClassNexus = new TeacherLessonClassNexus();
                                        teacherLessonClassNexus.setGmtCreate(new Date());
                                        teacherLessonClassNexus.setClassId(classInfo1.get(0).getId());
                                        teacherLessonClassNexus.setTeacherLessonId(teacherLesson.getId());
                                        teacherLessonClassNexusMapper.insertSelective(teacherLessonClassNexus);
                                        teacherLessonClassNexus.setId(null);

                                        continue;
                                    }

                                    ClassInfo classInfo = new ClassInfo();
                                    classInfo.setGmtCreate(new Date());
                                    System.out.println(classItem + "::" + ti.getName());
                                    classInfo.setGrade(Short.valueOf(classItem.substring(classItem.length() - 4, classItem.length() - 2)));
                                    classInfo.setName(classItem);
                                    classInfoMapper.insertSelective(classInfo);

                                    TeacherLessonClassNexus teacherLessonClassNexus = new TeacherLessonClassNexus();
                                    teacherLessonClassNexus.setGmtCreate(new Date());
                                    teacherLessonClassNexus.setClassId(classInfo.getId());
                                    teacherLessonClassNexus.setTeacherLessonId(teacherLesson.getId());
                                    teacherLessonClassNexusMapper.insertSelective(teacherLessonClassNexus);
                                    teacherLessonClassNexus.setId(null);


                                    /*teacherLessonClassNexus.setTeacherLessonId(teacherLesson.getId());
                                    teacherLessonClassNexusMapper.insertSelective(teacherLessonClassNexus);*/

                                    TeacherClassNexusExample teacherClassNexusExample = new TeacherClassNexusExample();
                                    TeacherClassNexusExample.Criteria criteria = teacherClassNexusExample.createCriteria();
                                    criteria.andClassIdEqualTo(classInfo.getId()).andTeacherIdEqualTo(ti.getId());
                                    List<TeacherClassNexus> teacherClassNexuses = teacherClassNexusMapper.selectByExample(teacherClassNexusExample);

                                    if (teacherClassNexuses.isEmpty()) {
                                        TeacherClassNexus teacherClassNexus = new TeacherClassNexus();
                                        teacherClassNexus.setGmtCreate(new Date());
                                        teacherClassNexus.setClassId(classInfo.getId());
                                        teacherClassNexus.setTeacherId(ti.getId());
                                        teacherClassNexusMapper.insertSelective(teacherClassNexus);
                                    }
                                }
                                teacherLesson.setId(null);
                            }
                        }
                    }

                    index++;
                }
            }
            sqlSession.commit();
            sqlSession.close();
        }
    }

    private List<Byte[]> formatWeek(String week) {
        //a-b单双全周
        //a全周
        //a,b,c全周
        //a-b,b-c,c-d全周
        //a-b,c全周
        week = week.replaceAll("\\[(.+)]","$1");

        String[] weeks = week.split("\\?\\?");
        List<Byte[]> list = new ArrayList<>(weeks.length);
        for(String s : weeks) {
            Byte[] ig = new Byte[2];
            if (s.contains("-")) {
                String[] weekInfo = s.split("-");
                ig[0] = Byte.valueOf(weekInfo[0]);
                ig[1] = Byte.valueOf(weekInfo[1]);
            } else if(s.length() != 0) {
                ig[0] = Byte.valueOf(s);
                ig[1] = Byte.valueOf(s);
            } else {
                throw  new RuntimeException("周次录入错误");
            }
            list.add(ig);
        }

//        System.out.println(list.size() + "::lenweek");
        return list;
    }

    public String formatPeriod(String period) {
        return period.replace("节","");
    }

    public String[] formatClassroomAndClass(String classroomAndClass) {

        //无校区,无指定教室的公共必修课
        if (classroomAndClass.contains("教室信息缺失")) {
            classroomAndClass = classroomAndClass.replace("教室信息缺失","");
        }

        //缺失班级信息的体育课
        if (Objects.equals(classroomAndClass,"田径场(待定)")) {
            return new String[]{"田径场(待定)"};
        }
        //教室+班级
        //教室+教室说明+班级
        String[] strs = classroomAndClass.replaceAll("\\s{1}([^\\s]+[1-9]{1}\\d{3}[A-Za-z]?)",
                ",$1").split(",");

        return strs;
    }

}
